<template>
  <view class="flex-col">
    <nav-bar color="white" bg-color="black" title="打印预览" show-back></nav-bar>
    <web-view
      v-if="!isForceHide"
      :fullscreen="true"
      :webview-styles="{
        // height: height,
      }"
      :src="path"
      ref="refWebview"
      @message="getMessage"
    ></web-view>
  </view>
</template>

<script>
import { webviewLifeCycle, webviewMethods } from "@/utils/webview-utils.js";
import { revenueReportPreview } from "@/api";
import store from "@/store";
import dayjs from "dayjs";
import KingonH5Plugin from "@/king-components/js/KingonPlus";

// var wv;
export default {
  // components: { zuiTabBar },
  data() {
    return {
      // ...webviewLifeCycle.data(),
      isForceHide: false,
      wv: null,
      currentWebview: null,
      path: "/hybrid/html/print-preview.html",
      height: "100%",
      kbHeight: 0,
      // 请求数据
      queryParams: {},
    };
  },
  onLoad(opt) {
    // webviewLifeCycle.onLoad(opt);
    // const sys = uni.getSystemInfoSync();
    // 100 为 100rpx的值
    // const px = uni.upx2px(120);
    // console.log("getSystemInfoAsync", sys);
    // this.height = sys.screenHeight - px + "px";
    console.log("opt >>", opt, " /path:");
    this.queryParams = opt;
  },
  /** 组件下 */
  mounted() {
    // webviewLifeCycle.created();
    // #ifdef APP-PLUS
    console.log("mounted >?", this.$parent);
    // this.currentWebview = this.$parent.$scope.$getAppWebview();
    this.currentWebview = this.$scope.$getAppWebview();
    // 获取手机系统信息
    const info = uni.getSystemInfoSync();
    // 设置状态栏高度（H5顶部无状态栏小程序有状态栏需要撑起高度）
    this.statusBarHeight = info.statusBarHeight;
    console.log("info >", info);
    //设置高度样式
    // 100 为 100rpx的值
    // const px = uni.upx2px(120);
    // this.height = info.screenHeight - px + "px";
    // console.log('height', this.height)
    const ter = setTimeout(() => {
      console.log("mounted > setTimeout");
      this.wv = this.$scope.$getAppWebview().children()[0];
      // this.wv = this.currentWebview.children()[0];
      this.wv.setStyle({
        top: info.screenHeight / 10 + "px", //this.statusBarHeight,
        // height: this.height,
        scalable: true, //webview的页面是否可以缩放，双指放大缩小
      });
      clearTimeout(ter);
    }, 500); //如果是页面初始化调用时，需要延时一下
    /** webview 内input事件键盘调起 */
    //  监听键盘高度变化
    uni.onKeyboardHeightChange((obj) => {
      // 获取系统信息
      let _sysInfo = uni.getSystemInfoSync();
      let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight;
      let _diff = obj.height - _heightDiff;
      // 键盘高度
      this.kbHeight = (_diff > 0 ? _diff : 0) - 2;
      console.log("kbHeight_>", this.kbHeight);
    });
    // 同时监听页面变化
    uni.onWindowResize((res) => {
      // TODO 因为设置了v-show 而不是 v-if 需要处理非处于当前页面时的
      console.log("onWindowResize:", res);

      if (res.size.windowHeight < parseInt(this.height)) {
        setTimeout(() => {
          this.wv.setStyle({
            // top: this.barHeight,
            top: 0,
            // webview的高度动态修改为减去键盘高度后的
            height: parseInt(this.height) - this.kbHeight,
            bottom: 0,
          });
        }, 100);
      } else {
        setTimeout(() => {
          // const info = uni.getSystemInfoSync();
          // 100 为 100rpx的值
          const px = uni.upx2px(120);
          // this.height = (info.screenHeight - px) + 'px';
          // this.reSizeWV();
          this.wv.setStyle({
            top: null,
            height: this.height,
            // bottom: -px,
            bottom: null,
            scalable: false, //webview的页面是否可以缩放，双指放大缩小
          });
        }, 100);
      }
    });
    // #endif
  },

  methods: {
    // 调用 webview 内部逻辑
    evalJs(funcName, data) {
      // wv = this.currentWebview.children()[0];
      // // this.evalJs(`${funcName}(${JSON.stringify(data)})`);
      this.wv?.evalJS(`${funcName}(${JSON.stringify(data)})`);
      // this.$refs.refWebview?.evalJS(`${funcName}(${JSON.stringify(data)})`);
    },
    // webview向外部发送消息
    getMessage(event) {
      const messageData = event.detail.data[0];
      if (messageData.api == "onWebviewShowed") {
        this.getData();
      }
      // API_> 生成图片
      else if (messageData.api == "onGenerateImageSuccess") {
        this.onGenerateImageSuccess(messageData.data);
      } else {
        // 其他预置的webview方法
        webviewMethods.getMessage(event);
      }
    },
    async getData() {
      // uni.showLoading({ title: "加载中", mask: true });
      try {
        const { data, success } = await revenueReportPreview(this.queryParams);
        // if (!success) throw Error("获取数据失败");
        this.dataList = data;
        // 向H5页面发送消息
        console.log("向H5页面发送消息: evalJs-apiChannel");
        this.evalJs("apiChannel", {
          API: "setData",
          DATA: {
            key: "dataList",
            data: {
              dataList: this.dataList,
              otherInfo: {
                // 商家名称
                businessName: store.getters.businessInfo.businessName,
                // 打印人
                printPerson: store.getters.userInfo.name,
                // 打印日期
                printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                // 统计日期
                statisticalDate: this.queryParams.startDate,
              },
            },
          },
        });
        uni.hideLoading();
      } catch (error) {
        console.error("获取数据失败#", JSON.stringify(error));
        uni.hideLoading();
        uni.showToast({
          title: error?.data?.msg || "获取数据失败",
          icon: "none",
        });
      }
    },
    onGenerateImageSuccess(e) {
      console.log("messageData.api onGenerateImageSuccess >", e);
      // 获取到base64, 输出打印

      // 打印
      const Arg = JSON.stringify({
        PrintData: [{ ActionType: "PrintBitmapBase64", Parameter: this.removeBase64(e) }],
      });

      // 将打印预览数据转换为base64格式
      KingonH5Plugin.execFunction(
        "koPrintReceipt",
        Arg,
        (result) => {
          uni.showToast({ title: "打印成功", icon: "none" });
          this.evalJs("apiChannel", {
            API: "changeLoading",
            DATA: {
              key: "dataList",
              data: { status: false },
            },
          });
          console.log("打印结果", JSON.parse(result));
          plus.nativeUI.alert(JSON.parse(result).message);
        },
        (result) => {
          this.evalJs("apiChannel", {
            API: "changeLoading",
            DATA: {
              key: "dataList",
              data: { status: false },
            },
          });
          uni.showToast({ title: "打印失败", icon: "none" });
          console.log("打印失败", JSON.parse(result));
          plus.nativeUI.alert(JSON.parse(result).message);
        }
      );
    },
    // 强制隐藏/显示
    forceHide(state = false) {
      this.isForceHide = state;
    },
    // 删除base64标识
    removeBase64(str) {
      return str.replace("data:image/png;base64,", "");
    },
  },
};
</script>

<style scoped></style>
